<template>
  <div class="app-container" v-loading="pageLoading">
    <el-row :gutter="10">
      <el-col :span="8">
        <div class="panel-info">
          <div class="panel-title">BOM列表</div>
          <div class="panel-body">
            <el-button type="primary" class="fr" @click="OpenMainModal" v-permission="'bom.add'">创建</el-button>
            <el-button type="success" class="fr" @click="importVisible = true" style="margin-right: 5px"
              v-permission="'bom.add'">导入
            </el-button>
            <div class="filter-container">
              <el-input style="width:240px" placeholder="输入BOM编号按回车" clearable prefix-icon="el-icon-search"
                class="filter-item" @keyup.enter.native="researchMain" @clear="researchMain"
                v-model="queryMain.queryString"></el-input>
              <el-button class="filter-item" type="success" plain @click="researchMain">查询</el-button>
            </div>
            <z-table :list="listMain" :tableProps="tablePropsMain" @current-change="getItemList" :columns="columnsMain"
              @editItem="editMain" @deleteItem="deleteMain">
              <template v-slot:content="v">
                <span v-if="v.key === 'forbid_flag'" class="text-label" :class="statusClass[v.row['forbid_flag']]">
                  {{ status[v.row['forbid_flag']] }}
                </span>
                <span v-else>{{ v.row[v.key] }}</span>
              </template>
              <template v-slot:operation="v">
                <a href="#" class="text-blue" @click.prevent="editMain(v.row, 2)" v-permission="'bom.add'">复制&nbsp;</a>
                <a href="#" class="text-yellow" v-if="v.row.forbid_flag == 'N'"
                  @click.prevent.stop="enableOrdisableBom(v.row)" v-permission="'bom.edit'">禁用&nbsp;</a>
                <a href="#" class="text-yellow" v-if="v.row.forbid_flag == 'Y'"
                  @click.prevent="enableOrdisableBom(v.row)" v-permission="'bom.edit'">开启&nbsp;</a>
                <a href="#" class="text-red" @click.prevent="deleteMain(v.row)" v-permission="'bom.delete'">删除</a>
              </template>
            </z-table>

            <z-pagination :pagination="paginationMain" :total="totalMain" :page.sync="queryMain.page"
              :limit.sync="queryMain.size" @change="getMainList"></z-pagination>
          </div>
        </div>
      </el-col>
      <el-col :span="16">
        <div class="panel-info" v-show="itemFlag">
          <div class="panel-title">BOM物料列表</div>
          <div class="panel-body">
            <div style="padding:  0; min-height: 40px">
              <el-button class="fr" @click="createItem" type="primary" plain>添加物料</el-button>
              <el-input style="width: 300px;margin-right:5px" placeholder="输入物料号查询按回车" clearable
                prefix-icon="el-icon-search" class="filter-item" @keyup.enter.native="research" @clear="research"
                v-model="query.queryString">
              </el-input>
              <el-button class="filter-item " type="success" plain @click="research">查询</el-button>
              <el-button class="filter-item" type="info" plain @click="exportData" :loading="exportLoading">导出
              </el-button>
            </div>
            <z-table :list="list" :tableProps="tableProps" :columns="columns" @editItem="editItem"
              @deleteItem="deleteItem">
            </z-table>
            <z-pagination :pagination="pagination" :total="total" :page.sync="query.page" :limit.sync="query.size"
              @change="getList"></z-pagination>
          </div>
        </div>
      </el-col>
    </el-row>
    <z-form-dialog v-move :name="name" :data="data" :formProps="formProps" :fields="fields" @submit="submit"
      :submitLoading="submitLoading" :visible.sync="editFormVisible">
      <template v-slot:operation>
        <el-button type="success" @click="saveWithNext" :loading="submitLoading">保存并继续添加</el-button>
      </template>
    </z-form-dialog>
    <el-dialog title="导入" width="50%" :visible.sync="importVisible">
      <div style="padding-right: 60px">
        <div style="margin-bottom: 10px"><a href="#" @click.prevent="getTemp1">下载导入模板</a></div>
        <upload-excel-component ref="uploadExcel" :on-success="handleSuccess" :before-upload="beforeUpload"
          style="margin-bottom: 20px" />
        <el-button type="primary" @click.native="importSave" :loading="importSaveLoading"> 确认 </el-button>
        <el-button @click="importVisible = false">取消</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="mainTitle" width="50%" :visible.sync="editMainFormVisible" :close-on-click-modal="false">
      <div style="padding-right: 60px">
        <el-form ref="dataMain" :model="dataMain" label-width="80px">
          <el-form-item label="BOM编号">
            <el-input v-model="dataMain.bom_no" :disabled="mainDisable"></el-input>
          </el-form-item>
          <el-form-item label="版本">
            <el-input v-model="dataMain.bom_version"></el-input>
          </el-form-item>
          <el-form-item label="BOM日期">
            <el-date-picker format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="dataMain.bom_date"></el-date-picker>
          </el-form-item>
        </el-form>
        <div class="text-right">
          <el-button type="primary" @click.native="saveMain" :loading="submitLoading"> 确认 </el-button>
          <el-button @click="editMainFormVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import commonMixin from '@/views/_common/mixin'
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
export default {
  mixins: [commonMixin],
  name: 'bom',
  components: { UploadExcelComponent },
  data: function () {
    return {
      api: this.$api.bom,
      apiEdit: this.$api.bom + 'add',
      name: 'BOM物料',
      columnsMain: [
        { title: 'BOM编码', key: 'bom_no' },
        { title: '版本', key: 'bom_version', width: 60 },
        { title: '状态', key: 'forbid_flag', width: 70 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '修改时间', key: 'modify_time', width: 140 },
      ],
      columns: [
        /*{title: 'BOM编码', key: 'bom_no', width: 140},*/
        { title: '物料编码', key: 'key_part_no', width: 120 },
        { title: '物料名', key: 'key_part_name', width: 140 },
        { title: '拣料类别', key: 'part_mode', width: 80 },
        // { title: '替代群组', key: 'kp_relation', width: 70 },
        //{title: 'BOM版本', key: 'bom_version', width: 100},
        { title: '数量', key: 'qty', width: 50 },
        { title: '单位', key: 'unit_mode', width: 50 },
        { title: '报废率', key: 'wastage_rate', width: 60 },
        { title: '顺序', key: 'sequence', width: 80 },
        { title: '系统捡料', key: 'pick_flag', width: 80 },
        { title: '备注', key: 'remarks', width: 100 },
        { title: '修改人', key: 'modify_user', width: 100 },
        { title: '最后修改', key: 'modify_time', width: 140 },
      ],
      fields: [
        { title: '顺序', key: 'sequence', required: true, span: 8, name: 'number', props: { min: 0, step: 1 } },
        {
          title: '物料编码',
          key: 'material_id',
          span: 24,
          name: 'select',
          options: [],
          props: {
            filterable: true,
            remote: true,
            remoteMethod: null,
          },
          required: true,
        },
        { title: '拣料类别', key: 'part_mode', span: 12, name: 'select', options: [], required: true },
        { title: '数量', key: 'qty', span: 8, name: 'number', props: { min: 0, step: 1 }, required: true },
        { title: '单位', key: 'unit_mode', span: 8 },
        { title: '报废率', key: 'wastage_rate', span: 8, name: 'number', props: { min: 0, step: 1 } },
        {
          title: '系统捡料',
          key: 'pick_flag',
          span: 8,
          name: 'switch',
          props: { inactiveValue: 'N', activeValue: 'Y' },
        },
        { title: '备注', key: 'remarks', span: 24, name: 'texarea' },
      ],
      initData: {
        material_id: null,
        part_mode: '',
        pick_flag: 'Y',
      },
      tablePropsMain: {
        'highlight-current-row': true,
        border: true,
        opsColWith: '120',
      },
      dataMain: {},
      editMainFormVisible: false, //编辑模态框的显示状态
      listMain: [],
      totalMain: 0,
      queryMain: {
        queryString: null,
        page: 1,
        size: 10,
      },
      itemFlag: false,
      type: '',
      mainTitle: '',
      mainDisable: true,
      status: { N: '已启用', Y: '已禁用' },
      statusClass: { Y: 'bg-gray', N: 'bg-green' },
      paginationMain: {
        //分页组件配置 如不需分页，可以把pagination设置为null
        layout: 'prev, pager, next, ->, total',
      },
      importSaveLoading: false,
      importVisible: false,
      keypartnoOptions: [],
      filterOptions: {},
      relationOptions: [],
      filterMethod: '',
      meOptions: [],
      modeOptions: [],
      tableData: [],
      curBom: {},
      partModeOptions: [],
      addNums: 0,
    }
  },
  methods: {
    getTemp1() {
      console.log('导入')
      import('@/vendor/Export2Excel')
        .then((excel) => {
          excel.export_json_to_excel({
            header: [
              'BOM编码',
              'BOM版本',
              'BOM日期',
              '序号',
              '料号',
              '用量',
              '单位',
              '捡料代码',
              '损耗率',
              '系统捡料Y/N',
              '备注',
            ],
            data: [['test', '1.0', '2022-03-23', '1', '30371502', '10', 'cm', 'A', '0', 'Y', '备注']],
            filename: 'BOM' + '导入_',
          })
        })
        .catch(() => {})
    },
    researchMain() {
      this.clearMainData()
      this.query = {
        queryString: null,
        size: 10,
        page: 1,
      }
      this.queryMain.page = 1
      this.listMain = []
      this.totalMain = 0
      this.getMainList()
    },
    clearMainData() {
      this.itemFlag = false
      this.list = []
      this.curBom = {}
    },
    init() {
      this.$request(this.$api.dictionary + 'getchildren', {
        parentType: 'keypart_pickup_type',
      })
        .then((r) => {
          this.partModeOptions = r
        })
        .catch(() => {})
    },
    formatAfterGet(data) {
      //依据实际需求处理
      this.singleMaOptions(data.material_id)
      return data
    },
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 50
      if (isLt1M) {
        return true
      }
      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning',
      })
      return false
    },
    handleSuccess({ results, header }) {
      // console.log(Obect.values(results), 'results')
      // return
      this.excelData = [[]]
      results.forEach((v) => {
        let tmp = []
        header.forEach((i) => {
          tmp.push(v[i])
        })
        this.excelData.push(tmp)
      })

      /*this.tableHeader = header*/
    },
    createItem() {
      this.addNums = 0
      this.data = _.cloneDeep(this.initData)
      console.log(this.data)
      this.editFormVisible = true
      this.name = 'BOM物料 | ' + '编号：' + this.curBom.bom_no + ' 版本：' + this.curBom.bom_version + ' '
      this.setFieldOptions('part_mode', [], 'value', 'label')
    },
    editItem(v) {
      this.addNums = 1
      this.name = 'BOM物料 | ' + '编号：' + this.curBom.bom_no + ' 版本：' + this.curBom.bom_version + ' '
      this.data = _.cloneDeep(this.initData)
      this.pageLoading = true
      this.$request(this.api + 'getbyid', {
        id: v.id,
      })
        .then((r) => {
          this.pageLoading = false
          this.data = this.formatAfterGet(r)
          this.editFormVisible = true
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    importSave: function () {
      this.excelData.shift()
      let url = this.api + 'batchadd'
      if (this.excelData.length <= 0) {
        this.$message({
          message: '请先选择Excel',
          type: 'error',
        })
        return false
      }
      this.$request(url, this.excelData, 'post')
        .then((r) => {
          this.importSaveLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.importVisible = false
          this.excelData = [[]]
          this.$refs.uploadExcel.clearFile()
          this.getMainList()
          this.getList()
        })
        .catch(() => {
          this.importSaveLoading = false
        })
    },
    getMaOptions(query) {
      this.setFieldOptions('material_id', [])
      if (query) {
        this.$request(this.$api.mat + 'getmatandsku', {
          queryString: query,
        })
          .then((r) => {
            this.setFieldOptions('material_id', r, 'id', ['key_part_no', 'key_part_name'])
          })
          .catch(() => {})
      }
    },
    singleMaOptions(v) {
      this.setFieldOptions('material_id', [])
      if (v) {
        this.$request(this.$api.mat + 'getmatandsku', {
          id: v,
        })
          .then((r) => {
            this.setFieldOptions('material_id', r, 'id', ['key_part_no', 'key_part_name'])
          })
          .catch(() => {})
      }
    },
    saveWithNext() {
      this.submitLoading = true
      let url = this.api + 'add'
      if (this.apiCreate) {
        url = this.apiCreate
      }
      if (this.data.id) {
        url = this.api + 'update'
        if (this.apiEdit) {
          url = this.apiEdit
        }
      }
      let data = this.formatBeforeSave(this.data)

      let dataCopy = _.cloneDeep(this.data)
      dataCopy.material_id = ''

      this.$request(url, data, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.data = dataCopy
          this.getList()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    getItemList(v) {
      this.curBom = v
      if (!v) return
      this.itemFlag = true
      this.query.bom_id = v.id
      this.queryMain.bom_id = v.id
      this.getList()
    },
    getMainList() {
      this.pageLoading = true
      let url = this.api + 'getBomMainList'
      this.queryMain.bom_id = ''
      this.$request(url, this.queryMain)
        .then((r) => {
          this.pageLoading = false
          this.listMain = r.list
          this.totalMain = r.total
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    formatBeforeSave(data) {
      let tmp = _.cloneDeep(data)
      tmp.bom_id = this.curBom.id
      return tmp
    },
    editMain(v, type) {
      this.type = type
      if (this.type == 1) {
        this.mainDisable = true
        this.mainTitle = '编辑BOM'
      }
      if (this.type == 2) {
        this.mainDisable = false
        this.mainTitle = '复制BOM--会同时复制此BOM下的物料明细'
      }
      this.dataMain = {}
      this.pageLoading = true
      this.$request(this.api + 'getBomMainById', {
        id: v.id,
      })
        .then((r) => {
          this.pageLoading = false
          this.dataMain = this.formatAfterGet(r)
          this.editMainFormVisible = true
        })
        .catch(() => {
          this.pageLoading = false
        })
    },
    OpenMainModal() {
      this.type = 1
      this.mainTitle = '创建BOM'
      this.mainDisable = false
      this.editMainFormVisible = true
      this.dataMain = {
        forbid_flag: 'N',
      }
    },
    deleteMain(v) {
      this.$confirm('确定要删除这条记录？', '操作确认').then(() => {
        this.pageLoading = true
        let url = this.api + 'deleteMain'

        this.$request(url + '/' + v.id, {}, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.clearMainData()
            this.getMainList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    saveMain() {
      this.submitLoading = true
      let url = ''
      if (this.type == 1) url = this.api + 'addMain'
      if (this.type == 2) url = this.api + 'copyBom'
      let data = this.dataMain
      this.clearMainData()
      this.$request(url, data, 'post')
        .then((r) => {
          this.submitLoading = false
          this.$message({
            message: '操作成功',
            type: 'success',
          })
          this.editMainFormVisible = false
          this.getMainList()
        })
        .catch(() => {
          this.submitLoading = false
        })
    },
    enableOrdisableBom(v) {
      let status = { N: '禁用', Y: '开启' }
      this.$confirm('确定要' + status[v.forbid_flag] + '这条记录？', '操作确认').then(() => {
        this.clearMainData()
        this.pageLoading = true
        let formData = new FormData()
        formData.append('id', v.id)
        this.$request(this.api + 'enableOrdisableBom', formData, 'post')
          .then((r) => {
            this.pageLoading = false
            this.$message({
              message: '操作成功',
              type: 'success',
            })
            this.getMainList()
          })
          .catch(() => {
            this.pageLoading = false
          })
      })
    },
    getTemp() {
      import('@/vendor/Export2Excel')
        .then((excel) => {
          excel.export_json_to_excel({
            header: [
              '工单号（必须）',
              '机种(model)',
              '工单类型',
              '数量（必须）',
              '上线日期（必须,格式:20210401）',
              '预计产出日期（必须,格式:20210401）',
              'SKU（必须）',
              '客户料号(cust_sku)',
              '客户(cust_code)',
              'BOM编号（必须）',
              'BOM版本',
              '装配件说明',
            ],
            data: [[]],
            filename: '工单导入模板',
          })
        })
        .catch(() => {})
    },
    exportData() {
      let url = this.api + 'getlist'
      this.exportLoading = true
      let query = this.formatQuery(this.queryMain, true)
      query.flag = 1
      let columns = _.cloneDeep(this.columns)
      columns.unshift({ title: '状态', key: 'status' })
      columns.unshift({ title: 'BOM版本', key: 'bom_version' })
      columns.unshift({ title: 'BOM编码', key: 'bom_no' })
      this.$request(url, query)
        .then((r) => {
          var exprotList = this.formatList(r.list)
          import('@/vendor/Export2Excel')
            .then((excel) => {
              const filterVal = columns.map((item) => {
                return item.key
              })
              const tHeader = columns.map((item) => {
                return item.title || item.key
              })
              const data = exprotList.map((v) => filterVal.map((j) => v[j]))
              excel.export_json_to_excel({
                header: tHeader,
                data,
                filename: this.name + '_' + dayjs().format('YYYYMMDD'),
              })
              this.exportLoading = false
            })
            .catch((e) => {
              this.exportLoading = false
            })
        })
        .catch(() => {
          this.exportLoading = false
        })
    },
  },
  watch: {
    'data.material_id': {
      deep: true,
      // immediate: true,
      handler(n, o) {
        if (this.addNums > 1 && n != o) {
          let PART_MODE = ''
          if (this.data.part_mode) {
            PART_MODE = this.data.part_mode
          }
          this.$set(this.data, 'part_mode', '')
          this.$request(this.$api.mat + 'getmatandsku', {
            id: n,
          }).then((r) => {
            if (r.length != 0) {
              this.$request(this.$api.matprefix + 'getpickupcode', {
                kpn: r[0].key_part_no,
              }).then((res) => {
                if (res.length == 0) {
                  this.setFieldOptions('part_mode', [], 'value', 'label')
                  return
                }
                let arr = []
                for (let i = 0; i < this.partModeOptions.length; i++) {
                  for (let j = 0; j < res.length; j++) {
                    if (this.partModeOptions[i].value == res[j]) arr.push(this.partModeOptions[i])
                  }
                }
                this.setFieldOptions('part_mode', arr, 'value', 'label')
                if (PART_MODE) this.$set(this.data, 'part_mode', PART_MODE)
                // if (PART_MODE && arr.some((v) => v.value == PART_MODE)) this.$set(this.data, 'part_mode', PART_MODE)
                else this.$set(this.data, 'part_mode', res[0])
              })
            }
          })
        } else {
          this.addNums++
        }
      },
    },
  },
  created: function () {
    //this.getList()
    this.getMainList()
    this.init()
    this.getFieldConfig('material_id').props.remoteMethod = this.getMaOptions
  },
}
</script>
<style scoped></style>
